/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.beyondsoft.common.core.util;

import com.beyondsoft.common.core.constant.CommonConstants;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Miscellaneous utilities for web applications.
 *
 * @author ry
 */
@Slf4j
@UtilityClass
public class WebUtils extends org.springframework.web.util.WebUtils {
    private final String UNKNOWN = "unknown";

    /**
     * 读取cookie
     *
     * @param name cookie name
     * @return cookie value
     */
    public String getCookieVal(String name) {
        HttpServletRequest request = WebUtils.getRequest();
        Assert.notNull(request, "request from RequestContextHolder is null");
        return getCookieVal(request, name);
    }

    /**
     * 读取cookie
     *
     * @param request HttpServletRequest
     * @param name    cookie name
     * @return cookie value
     */
    public String getCookieVal(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

    /**
     * 清除 某个指定的cookie
     *
     * @param response HttpServletResponse
     * @param key      cookie key
     */
    public void removeCookie(HttpServletResponse response, String key) {
        setCookie(response, key, null, 0);
    }

    /**
     * 设置cookie
     *
     * @param response        HttpServletResponse
     * @param name            cookie name
     * @param value           cookie value
     * @param maxAgeInSeconds maxage
     */
    public void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return {HttpServletRequest}
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取ip
     *
     * @return {String}
     */
    public String getIP() {
        return getIP(WebUtils.getRequest());
    }

    /**
     * 获取ip
     *
     * @param request HttpServletRequest
     * @return {String}
     */
    public String getIP(HttpServletRequest request) {
        Assert.notNull(request, "HttpServletRequest is null");
        String ip = request.getHeader("X-Requested-For");
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return StringUtils.isBlank(ip) ? null : ip.split(",")[0];
    }

    public String[] getUri(JoinPoint joinPoint) {
        String[] result = new String[]{"null", "null"};
        //获取请求根
        RequestMapping requestMapping = (RequestMapping) joinPoint.getSignature().getDeclaringType().getAnnotation(RequestMapping.class);
        //获取方法
        GetMapping getMapping = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(GetMapping.class);
        PostMapping postMapping = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(PostMapping.class);
        PutMapping putMapping = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(PutMapping.class);
        DeleteMapping deleteMapping = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(DeleteMapping.class);

        if (requestMapping != null) {
            String[] vs = requestMapping.value();
            if (vs != null && vs.length > 0) {
                result[0] = vs[0];
            }
        }
        if (getMapping != null) {
            result[1] = CommonConstants.REQUEST_GET;
            String[] vs = getMapping.value();
            if (vs != null && vs.length > 0) {
                result[0] += vs[0];
            }
        } else if (postMapping != null) {
            result[1] = CommonConstants.REQUEST_POST;
            String[] vs = postMapping.value();
            if (vs != null && vs.length > 0) {
                result[0] += vs[0];
            }
        } else if (putMapping != null) {
            result[1] = CommonConstants.REQUEST_PUT;
            String[] vs = putMapping.value();
            if (vs != null && vs.length > 0) {
                result[0] += vs[0];
            }
        } else if (deleteMapping != null) {
            result[1] = CommonConstants.REQUEST_DELETE;
            String[] vs = deleteMapping.value();
            if (vs != null && vs.length > 0) {
                result[0] += vs[0];
            }
        }
        return result;
    }

}

